<template>
  <a-spin :spinning="loading">
    <a-form :model="formState" ref="form" :rules="rules">
      <a-row>
        <a-col v-bind="colLayout">
          <a-form-item label="仓库">
            <a-input v-model:value="formState.warehouseCode" placeholder="请输入仓库"></a-input>
          </a-form-item>
        </a-col>
        <a-col v-bind="colLayout">
          <a-form-item label="站点" name="site">
            <a-select v-model:value="formState.site" placeholder="请选择站点" :options="siteList"/>
          </a-form-item>
        </a-col>
        <a-col v-bind="colLayout">
          <a-form-item label="船东">
            <a-input v-model:value="formState.shipOwner" placeholder="请输入船东"></a-input>
          </a-form-item>
        </a-col>
        <a-col v-bind="colLayout">
          <a-form-item label="时间（年-月）" name="time">
            <a-range-picker :placeholder="['开始时间', '结束时间']" picker="month" v-model:value="formState.time" valueFormat="YYYY-MM" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col v-bind="colLayout">
          <a-form-item label="时间（年-周）" name="time1">
            <a-range-picker  v-model:value="formState.time1" picker="week" value-format="YYYY-MM-DD"/>
            <!--            <a-range-picker :placeholder="['开始时间', '结束时间']" picker="month" v-model:value="formState.time" style="width: 100%" valueFormat="YYYY-MM" />-->
          </a-form-item>
        </a-col>
        <a-col v-bind="colLayout">
          <a-form-item>
            <a-button type="primary" @click="search">查询</a-button>
            <a-button type="primary" @click="reset" style="margin-left: 10px">重置</a-button>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <a-row :gutter="20">
      <a-col v-bind="{xl: 12, lg: 12, md: 24, sm: 24, xs: 24}" style="margin-bottom: 20px;">
        <a-card style="height:600px;width:100%">
          <div
              class="line-chart"
              ref="headChart"
          ></div>
        </a-card>
      </a-col>
      <a-col v-bind="{xl: 12, lg: 12, md: 24, sm: 24, xs: 24}" style="margin-bottom: 20px;">
        <a-card style="height:600px;width:100%">
          <div
              class="line-chart"
              ref="countPerMonthChart"
          ></div>
        </a-card>
      </a-col>
      <a-col v-bind="{xl: 12, lg: 12, md: 24, sm: 24, xs: 24}" style="margin-bottom: 20px;">
        <a-card style="height:600px;width:100%">
          <div
              class="line-chart"
              ref="countPerWeekChart"
          ></div>
        </a-card>
      </a-col>
      <a-col v-bind="{xl: 12, lg: 12, md: 24, sm: 24, xs: 24}" style="margin-bottom: 20px;">
        <a-card style="height:600px;width:100%">
          <a-row>
            <a-col v-bind="{xs: 24, sm: 24, md: 12, lg: 12, xl: 12}">
              <div
                  class="line-chart"
                  ref="pieChart1"
              ></div>
            </a-col>
            <a-col v-bind="{xs: 24, sm: 24, md: 12, lg: 12, xl: 12}">
              <div
                  class="line-chart"
                  ref="pieChart2"
              ></div>
            </a-col>
          </a-row>
        </a-card>
      </a-col>
    </a-row>
  </a-spin>
</template>
<script setup>
import CommonSearch from "@/components/commonSearch/index.vue";
import {getManyDictItems} from "@/api/system/dict.js";
import {message} from "ant-design-vue";
import {
  getHeadShippingDayCount,
  getHeadContainerCountPerMonth,
  getHeadContainerCountPerWeek, getHeadContainerCountPerDay, getHeadContainerCountSendWarehouseDoing
} from "@/api/head/index.js";
import {getBeforeMonthDate} from "@utils/utils.js";
import dayjs from "dayjs";
import {useEcharts} from "@/hooks/echarts/useEcharts.js";
import {ref} from "vue";
const colLayout = {
  xs: 24,
  sm: 12,
  md: 12,
  lg: 6,
  xl: 6,
  xxl: 6
}

const rules = {
  site:[{required: true, message: '请选择站点', trigger: 'blur'}],
  time:[{type: 'array', required: true, message: '请选择月', trigger: 'blur'}],
  time1:[{type: 'array', required: true, message: '请选择周', trigger: 'blur'}]
}
let instance1
let instance2
let instance3
let instance4
let instance5
const headChart = ref();
const countPerMonthChart = ref();
const countPerWeekChart = ref();
const pieChart1 = ref();
const pieChart2 = ref();
const form = ref()
const siteList = ref([])
const loading = ref(false)
const colorObj = {
  'ZONE_CA装柜-开船':'#FFEE99',
  'ZONE_NJ装柜-开船':'#FFB7DD',
  'ALL装柜-开船':'#FF7744',
  'ZONE_TX装柜-开船':'#99DD00',
  'ZONE_CA开船-到港':'#FFCC22',
  'ZONE_NJ开船-到港':'#FF44AA',
  'ALL开船-到港':'#FF5511',
  'ZONE_TX开船-到港':'#66DD00',
  'ZONE_CA到港-入仓':'#FFBB00',
  'ZONE_NJ到港-入仓':'#FF0088',
  'ALL到港-入仓':'#E63F00',
  'ZONE_TX到港-入仓':'#00DD00',
  'ZONE_CA入仓-上架':'#DDAA00',
  'ZONE_NJ入仓-上架':'#C10066',
  'ALL入仓-上架':'#C63300',
  'ZONE_TX入仓-上架':'#00DD77',
  'ZONE_CA上架':'#F0BBFF',
  'ZONE_NJ上架':'#E38EFF',
  'ALL上架':'#E93EFF',
  'ZONE_TX上架':'#CC00FF',
  'ZONE_CA发货':'#66FFFF',
  'ZONE_NJ发货':'#40bbfd',
  'ALL发货':'#00FFFF',
  'ZONE_TX发货':'#0066FF',
  'ZONE_CA':'#00DD77',
  'ZONE_TX':'#00BBFF',
  'ZONE_NJ':'#bd32d0',
  'ALL':'#C63300'
}
let formState = reactive({
  warehouseCode:"",
  site:"US",
  shipOwner:"",
  time:getBeforeMonthDate(3,'month'),
  shippingMonthBegin:"",
  shippingMonthEnd:"",
  time1:getBeforeMonthDate(1,'day')
  // time1:['2022-04-01','2022-08-01']
})
const search = async () => {
  try{
    const valid = await form.value.validate()
    try{
      loading.value = true
      for (let formStateKey in formState) {
        if(formState[formStateKey] === undefined || formState[formStateKey] === null || formState[formStateKey] === ""){
          delete formState[formStateKey]
        }
      }
      formState.shippingMonthBegin = formState.time[0]
      formState.shippingMonthEnd = formState.time[1]
      formState.dateBegin = formState.time1[0]
      formState.dateEnd = formState.time1[1]
      await Promise.all([
        initHeadShippingData(),
        getHeadContainerCountPerMonthData(),
        getHeadContainerCountPerWeekData(),
        getPieData()
      ])
    }catch (e){
      console.log(e)
      message.error(e)
    }finally {
      loading.value = false
    }
  }catch (e){
    console.log(e)
    // message.error(e)
  }
}
const reset =  () => {
  formState = {
    warehouseCode:"",
    site:"US",
    shipOwner:"",
    time:getBeforeMonthDate(3,'month'),
    shippingMonthBegin:"",
    shippingMonthEnd:"",
    time1:getBeforeMonthDate(1,'day')
  }
  search()
}
const initHeadShippingData = async () => {
  try{
    const res = await getHeadShippingDayCount(formState)
    // 判断对象是否为空
    if(Object.keys(res.result).length === 0){
      message.error("没有数据")
    }
    let obj = {}
    for (let resultKey of res?.result) {
      console.log(resultKey)
      for (let resultKeyKey in resultKey) {
        obj[resultKeyKey] = resultKey[resultKeyKey]
      }
    }
    let {seriesData, headShippingX,dataObj,stackArr} = fixData(obj,'dayCount',5,'right',['装柜-开船', '开船-到港', '到港-入仓', '入仓-上架'],['ZONE_CA','ZONE_TX','ZONE_NJ','ALL'])
    for(let i = 0; i< seriesData.length; i++){
      for (let dataObjKey in dataObj) {
        let num = dataObj[dataObjKey].find(data => {
          return data.name === seriesData[i].name
        })?.dayCount
        seriesData[i].data.push(num)
      }
    }
    seriesData.push(...statistics(headShippingX,seriesData,stackArr))
    const { initChart } = useEcharts(
        instance1,
        headChart,
        change({seriesData, headShippingX,xAxisName:'月份',yAxisName:'天数',title:'头程航程各阶段天数'})
    );
    initChart()
  }catch (e){
    console.log(e)
    message.error(e)
  }
}

const statistics = (headShippingX,seriesData,stackArr) => {
  let sumResult = []
  for(let i = 0; i < headShippingX.length; i++){
    let obj = {}
    obj.date = headShippingX[i]
    for(let j = 0; j < stackArr.length; j++){
      let sum = 0
      for(let k = 0; k < seriesData.length; k++){
        if(seriesData[k].stack === stackArr[j]){
          sum = sum + parseInt(seriesData[k].data[i] === undefined ? 0 : seriesData[k].data[i])
        }
      }
      obj[stackArr[j]] = sum
    }
    sumResult.push(obj)
  }
  let sumArr = []
  for(let j = 0; j < stackArr.length; j++){
    sumArr.push({
      stack:stackArr[j],
      name:'',
      data:headShippingX.map(item => 0),
      label: {
        show: true,
        position: 'top',
        formatter: function (params) {
          return stackArr[j] + ':' + sumResult.map(item => item[stackArr[j]])[params.dataIndex];
        }
      },
      type:'bar',
      emphasis: {
        focus: 'series'
      },
    })
  }
  return sumArr
}

const change = ({seriesData, headShippingX,xAxisName,yAxisName,title,}) => {
  return {
    title:{
      text:title,
      left: 'center',
      top:'5%'
    },
    tooltip: {
      trigger: 'item',
    },
    legend: {
      type: 'scroll',
      data: seriesData.map(item => item.name),
      // padding: [40, 11, 20, 37]
    },
    grid: {
      bottom: '0%',
      // top: '3%',
      containLabel: true,
    },
    xAxis: [
      {
        type: 'category',
        data: headShippingX,
        name:xAxisName,
      }
    ],
    yAxis: [
      {
        type: 'value',
        name:yAxisName
      }
    ],
    series:seriesData
  };
}
const change1 = ({seriesData, headShippingX,xAxisName,yAxisName,title}) => {
  return {
    title:{
      text:title,
      left: 'center',
      top:'5%'
    },
    tooltip: {
      trigger: 'item',
      formatter: function (value) {
        let arr = value.name.split('-')
        return `
        <div>
            <div>${value.seriesName}</div>
            <div style="width:110px">
              <div>
                <span style="color:${value.color};font-size:20px">●</span>
                <span>${arr[0]}W${arr[1]}</span>
              <span/>
              <span style="font-weight: bold;margin-left: 15px">${value.data}</span>
            </div>
        </div>
          `

      }
    },
    legend: {
      type: 'scroll',
      data: seriesData.map(item => item.name),
      // padding: [40, 11, 20, 37]
    },
    grid: {
      bottom: '0%',
      // top: '3%',
      containLabel: true,
    },
    xAxis: [
      {
        type: 'category',
        data: headShippingX,
        name:xAxisName,
        axisLabel: {
          formatter:  (value) => {
            let arr = value.split('-')
            return arr[0] + 'W' + arr[1]
          }
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name:yAxisName
      }
    ],
    series:seriesData
  };
}
const getHeadContainerCountPerMonthData = async () => {
  try{
    const res = await getHeadContainerCountPerMonth(formState)
    if(Object.keys(res.result).length === 0){
      message.error("没有数据")
    }
    let obj = {}
    for (let resultKey of res?.result) {
      for (let resultKeyKey in resultKey) {
        obj[resultKeyKey] = resultKey[resultKeyKey]
      }
    }
    let {seriesData, headShippingX,dataObj,stackArr} = fixData(obj,'cmt',8,'left',['上架','发货'])
    for(let i = 0; i< seriesData.length; i++){
      for (let dataObjKey in dataObj) {
        let num = dataObj[dataObjKey].find(data => {
          return data.name === seriesData[i].name
        })?.cnt
        seriesData[i].data.push(num)
      }
    }
    seriesData.push(...statistics(headShippingX,seriesData,stackArr))
    const { initChart } = useEcharts(
        instance2,
        countPerMonthChart,
        change({seriesData, headShippingX,xAxisName:'月份',yAxisName:'柜子数',title:'头程各方向柜子数-每月'})
    );
    initChart()
  }catch (e){
    console.log(e)
  }
}
const getHeadContainerCountPerWeekData = async () => {
  try{
    const res = await getHeadContainerCountPerWeek(formState)
    if(Object.keys(res.result).length === 0){
      message.error("没有数据")
    }
    let obj = {}
    for (let resultKey of res?.result) {
      for (let resultKeyKey in resultKey) {
        obj[resultKeyKey] = resultKey[resultKeyKey]
      }
    }
    let {seriesData, headShippingX,dataObj,stackArr} = fixData(obj,'cnt',8,'left',['上架','发货'],'week')
    for(let i = 0; i< seriesData.length; i++){
      for (let dataObjKey in dataObj) {
        let num = dataObj[dataObjKey].find(data => {
          return data.name === seriesData[i].name
        })?.cnt
        seriesData[i].data.push(num)
      }
    }
    seriesData.push(...statistics(headShippingX,seriesData,stackArr))
    const { initChart } = useEcharts(
        instance3,
        countPerWeekChart,
        change1({seriesData, headShippingX,xAxisName:'周',yAxisName:'柜子数',type:'week',title:'头程各方向柜子数-每周'})
    );
    initChart()
  }catch (e){
    console.log(e)
  }
}
const getPieData = async () => {
  try{
    const res1 = await getHeadContainerCountPerDay()
    const res2 = await getHeadContainerCountSendWarehouseDoing()
    let option1 = {
      title:{
        text: 'US海上在途柜子数',
        left: 'center',
        top:'10%'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        left: 'center'
      },
      series: [
        {
          type: 'pie',
          radius: '75%',
          data: res1.result.map(item => {
            return {
              value:item.count,
              name:item.saleZone,
              itemStyle:{
                color:colorObj[item.saleZone] || ''
              }
            }
          }),
          label:{
            position:'inner',
            formatter: (params) =>  params.value,
            fontSize:20
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    let option2 = {
      title:{
        text:'US送仓柜子数',
        left: 'center',
        top:'10%'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        left: 'center'
      },
      series: [
        {
          type: 'pie',
          radius: '75%',
          data: res2.result.map(item => {
            console.log(item.saleZone)
            return {
              value:item.count,
              name:item.saleZone,
              itemStyle:{
                color:colorObj[item.saleZone] || ''
              }
            }
          }),
          label:{
            position:'inner',
            formatter: (params) => params.value,
            fontSize:20
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 36,
              shadowOffsetX: 0,
              shadowColor: 'rgba(119,8,8,0.5)'
            }
          }
        }
      ]
    }
    const { initChart:initChart1 } = useEcharts(instance4, pieChart1, option1)
    const { initChart:initChart2 } = useEcharts(instance5, pieChart2, option2)
    initChart1()
    initChart2()
  }catch (e){
    console.log(e)
    message.error(e)
  }
}
/**
 * 处理数据
 * @param res 返回结果
 * @param value 要获取的值
 * @param num 需要截取的数量
 * @param direction 方向
 * @param arr 类型数组
 * @param type 类型
 * @returns {{seriesData: Array, headShippingX: Array, dataObj: Object, stackArr: Array}}
 */
const fixData = (res,value,num,direction,arr,type = 'month') => {
  let headShippingX = []
  let seriesData = []
  for (let resultKey in res) {
    headShippingX.push(resultKey)
  }
  let dataObj = {}
  if(type === 'month'){
    let dayjsDates = headShippingX.map(date => dayjs(date));
    let sortedDates = dayjsDates?.sort((a, b) => a.isBefore(b) ? -1 : 1);
    headShippingX = sortedDates?.map(date => date.format('YYYY-MM'));
  }
  headShippingX.forEach(item => {
    for (let resultKey in res) {
      if(item === resultKey){
        dataObj[item] = res[item]
      }
    }
  })
  for (let resultKey in dataObj) {
    for (let i = 0; i < arr.length; i++) {
      for (let j = 0; j < dataObj[resultKey].length; j++) {
        if (dataObj[resultKey][j].type === arr[i]) {
          dataObj[resultKey][j].name = dataObj[resultKey][j].saleZone + dataObj[resultKey][j].type
        }
      }
    }
  }
  let arr2 = []
  for (let dataObjKey in dataObj) {
    arr2.push(...dataObj[dataObjKey])
  }
  arr2 = [...new Set(arr2.map(item => item.name))]
  arr2.forEach(name => {
    let obj = {
      name:name,
      type: 'bar',
      stack: direction === 'right' ? name.substring(0, name.length - num) : (name.includes("ALL") ? name.substring(3, name.length) : name.substring(7, name.length)),
      emphasis: {
        focus: 'series'
      },
      label: {
        show: true,
        formatter: (params) => params.value,
      },
      itemStyle:{
        color:colorObj[name] || ''
      },
      data:[]
    }
    seriesData.push(obj)
  })
  let stackArr = [... new Set(seriesData.map(item => item.stack))]
  return {seriesData,headShippingX,dataObj,stackArr }
}
const init = async () => {
  try{
    const res = await getManyDictItems({
      dictCodeList:"site"
    })
    siteList.value = res.result.site
  }catch (e){
    console.log(e)
  }
}
onMounted(() => {
  init()
  search()
})
</script>
<style scoped lang="less">
:deep(.ant-form-item) {
  display: flex;
  padding-right: 10px;
  margin-top: 5px;
}

:deep(.ant-form-item-label) {
  display: inline-block;
  vertical-align: center;
  width: auto;
  margin-right: 5px;
}

:deep(.ant-form-row) {
  width: 100%;
}

:deep(.ant-form-item-control) {
  flex: 1 1;
}

:deep(.ant-form-item-control) {
  width: 70%;
}
.line-chart {
  width: 100%;
  height: 552px;
}
</style>
